#include <stdio.h>
#include <stdlib.h>
#include "linkqueue.h"

//创建
linkqueue queue_create() {

    linkqueue lq = (linkqueue)malloc(sizeof(linknode));
    if (lq == NULL) {
	printf("malloc linkqueue failed\n");
	return NULL;
    }

    lq->front = lq->rear = (linklist)malloc(sizeof(listnode));
    if (lq->front == NULL) {
	printf("malloc node failed\n");
	free(lq);
	return NULL;
    }

    lq->front->data = 0;
    lq->front->next = NULL;

    return lq;
}

//入队
int enqueue(linkqueue lq, data_t value) {

    if (lq == NULL) {
	printf("malloc linkqueue failed\n");
	return -1;
    }

    linklist p = (linklist)malloc(sizeof(linknode));
    if (p == NULL) {
	printf("malloc node failed\n");
	return -1;
    }

    p->data = value;
    p->next = NULL;

    lq->rear->next = p;
    lq->rear = p;

}


//出队
data_t dequeue(linkqueue lq){

    if (lq == NULL) {
	printf("malloc linkqueue failed\n");
	return -1;
    }

    if (lq->front->next == NULL) {
	printf("lq not data\n");
	return -1;
    }

    linklist p = lq->front;
    lq->front = p->next;
    free(p);
    p = NULL;

    return (lq->front->data);
}


//是否为空
int queue_empty(linkqueue lq){
    if (lq == NULL) {
	printf("malloc linkqueue failed\n");
	return -1;
    }

    return lq->front == lq->rear ? 1 : 0;
}


//清空
int queue_clear(linkqueue lq){
    if (lq == NULL) {
	printf("malloc linkqueue failed\n");
	return -1;
    }

    linklist p ;
    while (lq->front->next != NULL) {
	p = lq->front;
	lq->front = p->next;
	printf("clear:%d\n", p->data);
	free(p);
	p = NULL;
    }

    return 1;
}


//释放
linkqueue queue_free(linkqueue lq){
    if (lq == NULL) {
	printf("malloc linkqueue failed\n");
	return NULL;
    }

    linklist p;
    while (lq->front != NULL) {
	p = lq->front;
	lq->front = p->next;
	printf("free:%d\n", p->data);
	free(p);
    }

    free(lq);
    lq = NULL;
    p =NULL;
    return NULL;
}

//显示
void queue_show(linkqueue lq){
    if (lq == NULL) {
	printf("malloc linkqueue failed\n");
    }

    printf("队列中的元素: ");
    linklist p = lq->front;
    while (p->next != NULL){
	printf("%d ",p->next->data);
	p = p->next;
    }
    puts("");
}
